////////////////////////////////////////////////////////////////////////////////
// Copyright 2006 CORE Solutions Limited
// All rights reserved.
// PROPRIETARY AND CONFIDENTIAL INFORMATION.
// Use is subject to license terms.
//
// FUNCTION ID      :   TagLibUtil.java
// AUTHOR           :   ric.yik
// DATE CREATE      :   2006/6/23
// DESCRIPTION      :   
//                  :   
//                  :   
//                  :   
//
// MODIFICATION HISTORY:
// DATE         AUTHOR          VERSION NO.         COMMENT
// -----------  --------------  ------------------  -------------------
// 2006/6/23      ric.yik         1.0                 source is created.
//
//
//
////////////////////////////////////////////////////////////////////////////////

package com.erp.framework.controller.taglib;

import java.util.StringTokenizer;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;

import com.erp.framework.util.CommonUtil;

public class TagLibUtil {

    public static String resolveVariableBindings(PageContext pageContext, String property) throws JspException {
        if (property == null || property.indexOf('[') == -1) return property;
        StringTokenizer tokens = new StringTokenizer(property, "[]", true);
        StringBuffer result = new StringBuffer();
        while (tokens.hasMoreTokens()) {
            String token = tokens.nextToken();
            if ("[".equals(token)) {
                if (!tokens.hasMoreTokens()) throw new JspException("Invalid property name: " + property);
                result.append(token);
                token = tokens.nextToken();
                if ("[".equals(token) || "]".equals(token)) throw new JspException("Invalid property name: " + property);
                Object idx = token;
                if (!CommonUtil.isValidPositiveIntegerOrZero(String.valueOf(token))) {
                    idx = pageContext.findAttribute(token);
                    if (CommonUtil.isEmpty(idx) || !CommonUtil.isValidPositiveIntegerOrZero(String.valueOf(idx))) {
                        throw new JspException("Invalid index value inside property name: " + property + ", index: " + idx);
                    }
                }
                result.append(String.valueOf(idx));
                if (!tokens.hasMoreTokens()) throw new JspException("Invalid property name: " + property);
                token = tokens.nextToken();
                if (!"]".equals(token)) throw new JspException("Invalid property name: " + property);
                result.append(token);
            } else if ("]".equals(token)) {
                throw new JspException("Invalid property name: " + property);
            } else {
                result.append(token);
            }
        }
        return result.toString();
    }

}
